package com.suzhe.ymall.common.handler;

import com.suzhe.ymall.common.exception.AuthorizationException;
import com.suzhe.ymall.common.exception.YMallException;
import com.suzhe.ymall.common.pojo.ApiResEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * 统一异常处理器
 * @author suzhe
 * @date 2019/6/8
 */
@RestControllerAdvice
@Slf4j
public class YMExceptionHandler {


    /**
     * 处理自定义异常
     */
    @ExceptionHandler(YMallException.class)
    public ApiResEntity handleRRException(YMallException e){

        return ApiResEntity.error(e.getCode(),e.getMsg());
    }


    /**
     * 400 - Bad Request
     *
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ApiResEntity handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("缺少请求参数", e);
        return ApiResEntity.error("缺少请求参数");
    }

    /**
     * 400 - Bad Request
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ApiResEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("参数解析失败", e);
        return ApiResEntity.error("参数解析失败");
    }

    /**
     * 400 - Bad Request
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return  ApiResEntity.error(message);
    }


    /**
     * 400 - Bad Request
     */
    @ExceptionHandler(BindException.class)
    public ApiResEntity handleBindException(BindException e) {
        log.error("参数绑定失败", e.getMessage());
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return ApiResEntity.error(message);
    }

    /**
     * 400 - Bad Request
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ApiResEntity handleServiceException(ConstraintViolationException e) {
        log.error("参数验证失败", e.getMessage());
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        return  ApiResEntity.error(message);
    }

    /**
     * 400 - Bad Request
     */
    @ExceptionHandler(ValidationException.class)
    public ApiResEntity handleValidationException(ValidationException e) {
        log.error("参数验证失败", e);
        return  ApiResEntity.error("参数验证失败");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiResEntity handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return ApiResEntity.error("路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ApiResEntity handleAuthorizationException(AuthorizationException e){
        log.error(e.getMessage(), e);
        return ApiResEntity.error("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResEntity handleException(Exception e){
        log.error(e.getMessage(), e);
        return ApiResEntity.error("服务器出现内部错误，请联系管理员授权");
    }

}
